package com.cloudcc.mobile.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Environment;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.model.DynamicModel;
import com.cloudcc.cloudframe.model.DynamicModel.FeedFile;
import com.cloudcc.cloudframe.model.DynamicModel.Polls;
import com.cloudcc.cloudframe.util.ArrayUtils;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.NumberUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.DongHuaUtils;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.Myinformation;
import com.cloudcc.mobile.view.activity.UserInfoActivity;
import com.cloudcc.mobile.view.mymodel.isshuaxin;
import com.cloudcc.mobile.weight.GridViewForListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.log.Log;
import com.mypage.utils.ImageLoaderUtils_circle;
import com.mypage.utils.SaveTemporaryData;
import com.mypage.utils.VoiceMediaManager;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Decoder.BASE64Decoder;
import de.greenrobot.event.EventBus;

public class DynamicAdapter extends BaseAdapter {

	private String mEns = RunTimeManager.getInstance().getlanguage();
	 private AudioTrack mAudioTrack;//播放苹果格式语音caf
	/**
	 * 语音相关
	 */
	public String mVoiceData;//语音数据
	public String mVoiceName;//语音名字
	public String mVoiceTime;//语音时间（多少秒）
	public String mVoiceType;//语音格式
	public String mVoiceId;//语音ID
//	public View viewanim;
	private int mMinItemWith;// 设置对话框的最大宽度和最小宽度
	private int mMaxItemWith;
	public boolean mBamr = true;
	public SharedPreferences mSp;
	public String mId;//语音帖子id
	 private  String checkoption;
	
	

	private static final int TYPECOUNT = 7;// type类型

	/**
	 * 连接分享 L
	 */
	private static final int TYPE_LINK = 0;
	/**
	 * 图片分享 D
	 */
	private static final int TYPE_FILE = 1;
	/**
	 * 投票 V
	 */
	private static final int TYPE_VOTE = 2;
	/**
	 * 关系 G 系统跟踪创建
	 */
	private static final int TYPE_RELATION = 3;
	/**
	 * 啥也没有 F (关联)
	 */
	private static final int TYPE_FOLLOW = 4;
	/**
	 * 在 G下面 创建 快速 event
	 */
	private static final int TYPE_EVENT = 5;
	/**
	 * 出现语音的标识符
	 */
	private static final int TYPE_VOICE = 6;
	
	
	private OnItemListener onItemListener;

	private List<DynamicModel> mData = new ArrayList<DynamicModel>();
	private Context mContext;
	private LayoutInflater mInflater;

	private String voteCureentOption = StringUtils.EMPTY;
	private int currentVoteOpts = 0;
	private String targetid = null;
	private String name = null;
	private String tag = null;
	public DynamicAdapter(Context mContext) {
		super();
		SaveTemporaryData.detailDyamic = "";
		SaveTemporaryData.GeneralOne = true;
		this.mContext = mContext;
		mInflater = LayoutInflater.from(mContext);
		// 获取系统宽度
		WindowManager wManager = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wManager.getDefaultDisplay().getMetrics(outMetrics);
		mMaxItemWith = (int) (outMetrics.widthPixels * 0.7f);
		mMinItemWith = (int) (outMetrics.widthPixels * 0.15f);
		mSp = mContext.getSharedPreferences("users", Context.MODE_PRIVATE);
		
	}

	public DynamicAdapter(Context mContext, String string, String name,String tag) {
		super();
		this.mContext = mContext;
		this.targetid = string;
		this.name = name;
		this.tag = tag;
		mInflater = LayoutInflater.from(mContext);
		// 获取系统宽度
		WindowManager wManager = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wManager.getDefaultDisplay().getMetrics(outMetrics);
		mMaxItemWith = (int) (outMetrics.widthPixels * 0.7f);
		mMinItemWith = (int) (outMetrics.widthPixels * 0.15f);
		mSp = mContext.getSharedPreferences("users", Context.MODE_PRIVATE);
	}

	@Override
	public View getView(final int position, View convertView,
			final ViewGroup parent) {

		final DynamicModel dynamic = mData.get(position);

		int viewType = getItemViewType(position);
		if (viewType == TYPE_FOLLOW) {// 跟随
			convertView = BindViewForFollow(convertView);
		} else if (viewType == TYPE_LINK) {// 连接分享
			convertView = BindViewForLink(convertView);
		} else if (viewType == TYPE_FILE) {// 图片
			convertView = BindViewForFile(convertView);
		} else if (viewType == TYPE_RELATION) {// 关联
			convertView = BindViewForRelation(convertView);
		} else if (viewType == TYPE_VOTE) {//投票
			convertView = BindViewForVote(convertView);
		} else if (viewType == TYPE_EVENT) {
			convertView = BindViewForEvent(convertView);
		}else if(viewType == TYPE_VOICE){
			convertView = BindViewForVoice(convertView,dynamic,position);
		}
		ViewHolder vh = (ViewHolder) convertView.getTag();
		// 通用赋值
		fillDataCommon(dynamic, vh, position);
		// body
		setBodyByType(viewType, vh, dynamic);

		fillDataByType(viewType, vh, dynamic, position);

		return convertView;
	}

	private void fillDataByType(int viewType, ViewHolder vh,
			DynamicModel dynamic, int position) {
		final DynamicModel t = dynamic;
		switch (viewType) {
		case TYPE_LINK:// 连接
			// 链接
			vh.lianjiename.setText(dynamic.linkName);
			vh.linkContainer.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (onItemListener != null) {
						onItemListener.onClickLink(t);
					}
				}
			});

			break;
		case TYPE_FOLLOW:
			vh.gv.setVisibility(View.VISIBLE);
			break;
		case TYPE_FILE:// 图片文件
			vh.aboutpic.setVisibility(View.VISIBLE);
			if (dynamic.feedFile != null) {
				List<FeedFile> feedFiles = dynamic.feedFile;
				LayoutParams layoutParams = vh.gv.getLayoutParams();
				if (feedFiles.size() == 1) {
					vh.gv.setNumColumns(1);
					layoutParams.height = LayoutParams.WRAP_CONTENT;
					layoutParams.width = LayoutParams.WRAP_CONTENT;
				} else if (feedFiles.size() == 4) {
					vh.gv.setNumColumns(2);
					layoutParams.height = AppContext.screenW / 2;
					layoutParams.width = AppContext.screenW / 2;
				} else {
					vh.gv.setNumColumns(3);
					layoutParams.height = AppContext.screenW * 3 / 4;
					layoutParams.width = AppContext.screenW * 3 / 4;
				}
				vh.gv.setLayoutParams(layoutParams);
				if (feedFiles.size() > 0) {
					FeedFile fristFile = feedFiles.get(0);
					String type = fristFile.contentType;
					vh.downwenjian.setText(fristFile.filename + "." + type
							+ "(" + fristFile.fileLength + ")");
					if (isImageMima(type)) {
						vh.downloadpic.setVisibility(View.GONE);// 图片的话，把我要下载隐藏
						vh.downwenjian.setVisibility(View.GONE);
						vh.gv.setVisibility(View.VISIBLE);
						IndexGridViewAdapter adapter = new IndexGridViewAdapter(
								mContext, feedFiles);
						vh.gv.setAdapter(adapter);
					} else {
						vh.gv.setVisibility(View.GONE);
						vh.downloadpic.setVisibility(View.VISIBLE);// 文件的话，我要下载显示
						vh.downwenjian.setVisibility(View.VISIBLE);
					}
				}
			}
			break;
		case TYPE_RELATION:// 关联

			break;
		case TYPE_VOTE:// 投票
			fillDataForVote(vh, dynamic, position);
			break;
		case TYPE_EVENT:// 事件
			// fillDataForEvent(vh, dynamic);
			break;

		default:
			break;
		}

	}

	private void fillDataForVote(final ViewHolder vh, DynamicModel dynamic,
			final int position) {
		refreshVoteUI(vh, dynamic.polls, isVoteByMe(dynamic.polls));
		final DynamicModel t = dynamic;
		vh.bttoupiao.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (onItemListener != null) {
					currentVoteOpts = position;
					onItemListener.onClickVote(t, voteCureentOption);
				}
			}
		});
		vh.refreshvote.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				isshuaxin isshuaxin  = new isshuaxin();
				isshuaxin.isshua = true;
				EventBus.getDefault().post(isshuaxin);
			}
		});
		vh.btnSeeVote.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 查看结果
				String text = ((TextView) v).getText().toString();
				DynamicModel dynamicModel = getItem(position);
				if (StringUtils.equals("更改投票", text)) {
					refreshVoteUI(vh, dynamicModel.polls, false);
				} else if(StringUtils.equals("查看结果",text)){
					refreshVoteUI(vh, dynamicModel.polls, true);
				}
				if (StringUtils.equals("Modify vote", text)) {
					refreshVoteUI(vh, dynamicModel.polls, false);
				} else if(StringUtils.equals("View Results",text)){
					refreshVoteUI(vh, dynamicModel.polls, true);
				}
			}
		});
	}

	/**
	 * 刷新votte
	 * 
	 */
	public void refreshVote() {
		int viewType = getItemViewType(currentVoteOpts);
		if (viewType != TYPE_VOTE) {
			return;
		}
		DynamicModel dynamic = getItem(currentVoteOpts);
		if (dynamic.polls == null) {
			return;
		}
		String userId = UserManager.getManager().getUser().userId;
		// 先移除
		for (Polls itemPoll : dynamic.polls) {
			for (int i = 0; i < itemPoll.optionUsers.length; i++) {
				String item = itemPoll.optionUsers[i];
				if (StringUtils.equals(item, userId)) {
					itemPoll.optionUsers = ArrayUtils.remove(
							itemPoll.optionUsers, i);
				}
			}
		}

		for (Polls itemPoll : dynamic.polls) {
			String option = itemPoll.option;
			if (StringUtils.equals(option, voteCureentOption)) {
				String[] cacheUsers;
				if (itemPoll.optionUsers == null) {
					cacheUsers = new String[] { userId };
				} else {
					cacheUsers = new String[itemPoll.optionUsers.length + 1];
					for (int i = 0; i < itemPoll.optionUsers.length; i++) {
						cacheUsers[i] = itemPoll.optionUsers[i];
					}
					cacheUsers[cacheUsers.length - 1] = userId;
				}
				itemPoll.optionUsers = cacheUsers;
			}
		}
		notifyDataSetChanged();
	}

	/**
	 * 判断是不是 我投的票
	 */
	private boolean isVoteByMe(List<Polls> polls) {
		String userID = UserManager.getManager().getUser().userId;
		for (Polls pollItem : polls) {
			String[] optionUsers = pollItem.optionUsers;
			if (optionUsers == null || optionUsers.length == 0) {
				continue;
			}
			for (String optionUserId : pollItem.optionUsers) {
				if (StringUtils.equals(userID, optionUserId)) {

					return true;
				}
			}
		}
		return false;
	}
	//投票ui
	private void refreshVoteUI(final ViewHolder vh, List<Polls> polls,
							   boolean isResult) {
		String userID = UserManager.getManager().getUser().userId;
		int checki=0;
		int changetag=0;
		vh.abcapoll.removeAllViews();
		vh.bttoupiao.setVisibility(isResult ? View.GONE : View.VISIBLE);
		vh.btnSeeVote.setBackground(isResult?mContext.getResources().getDrawable(R.drawable.toupiaoselect):mContext.getResources().getDrawable(R.drawable.bg_write));
		//投票点击状态
		vh.bttoupiao.setTextColor(mContext.getResources().getColor(R.color.blue_overlay));
		vh.bttoupiao.setEnabled(false);
		if("true".equals(tag)){
			vh.jixu_tv.setVisibility(View.GONE);
			vh.wenben.setMaxLines(10);
			vh.refreshvote.setVisibility(View.GONE);
		}else{
			vh.refreshvote.setVisibility(isResult?View.VISIBLE:View.GONE);
		}
		if ("en".equals(mEns)) {
				vh.btnSeeVote.setText(isResult ? "Modify vote" : "View Results");
			}else{
				vh.btnSeeVote.setText(isResult ? "更改投票" : "查看结果");
		}
		

		if (polls == null || polls.size() < 0) {
			return;
		}

		// 获取 结果
		int count = 0;
		for (Polls p : polls) {
			String[] a = p.optionUsers;
			if (a != null) {
				count = count + a.length;
			}
		}
		vh.counttp.setText(count + "票");

		if (isResult) {// 投过票了 就展示结果
			for (int i = 0; i < polls.size(); i++) {
				Polls poll = polls.get(i);
				View v = LayoutInflater.from(mContext).inflate(
						R.layout.about_tp2, null);
				TextView tv = (TextView) v.findViewById(R.id.textView102);
				TextView bfb = (TextView) v.findViewById(R.id.percent);
				ProgressBar pb = (ProgressBar) v
						.findViewById(R.id.progressBar1);
				TextView bili = (TextView) v.findViewById(R.id.bili);
				tv.setText(poll.option);
				pb.setMax(count);
				pb.setProgress(poll.optionUsers.length);
				if(poll.optionUsers.length==0) {
				   bili.setVisibility(View.GONE);
				}
				bili.setText("(" + poll.optionUsers.length + "/" + count + ")");
				double c = (poll.optionUsers.length * 1.0) / count;
				DecimalFormat df1 = new DecimalFormat("0%");
				if (count == 0) {
					bfb.setText("0%");
				} else {
					bfb.setText(df1.format(c));
				}
				LayoutParams params = new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				vh.abcapoll.addView(v, params);
			}
		} else {// 没投票就展示投票
			// 先添加radiogroup
			RadioGroup radioGroup = new RadioGroup(mContext);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			vh.abcapoll.addView(radioGroup, params);
			for (int i = 0; i < polls.size(); i++) {
				Polls poll = polls.get(i);
				RadioButton radio = new RadioButton(mContext);
//				radio.setButtonDrawable(R.drawable.radio_button_sele);
				radio.setTextSize(13);
//				radio.setPadding(16,16,0,0);
//				radio.setTextColor(mContext.getResources().getColor(top_bar_text));
				//根据投票id获取是否投过票
				String[] optionUsers = poll.optionUsers;
				if (optionUsers != null || optionUsers.length != 0) {
					for (String optionUserId : poll.optionUsers) {
						if (StringUtils.equals(userID, optionUserId)) {
							changetag++;
							checki = i;
						}
					}
				}
				radio.setId(i);
				radio.setText(poll.option);
				radioGroup.addView(radio);
			}
			if(changetag!=0) {
				radioGroup.check(checki);
			}


			radioGroup
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(RadioGroup group,
								int checkedId) {
							RadioButton rb = (RadioButton) group
									.findViewById(checkedId);

//							vh.refreshvote = (Button) convertView.findViewById(R.id.refresh_vote);
							vh.bttoupiao.setTextColor(mContext.getResources().getColor(R.color.lanseziti));
							vh.bttoupiao.setEnabled(true);

							voteCureentOption = rb.getText().toString();
						}
					});

		}

	}

	private void fillDataForEvent(ViewHolder vh, DynamicModel dynamic) {
		if ("en".equals(mEns)) {

			vh.dynamic_event.setVisibility(StringUtils
					.isBlank(dynamic.taskOrEventName) ? View.GONE : View.VISIBLE);
			String srcName = dynamic.taskOrEventName;
			String eventName = "";
			boolean hasEvent = true;
			if (StringUtils.equals(srcName, "Record the phone")) {
				eventName = "Activity: Phone";
			} else if (StringUtils.equals(srcName, "Record SMS")) {
				eventName = "Record SMS";
			} else if (StringUtils.equals(srcName, "Sign in to visit")) {
				eventName = "Sign in to visit";
			} else if (StringUtils.equals(srcName, "Record mail")) {
				eventName = "Activity: Mail";
			} else if (StringUtils.equals(srcName, "Write a note")) {
				eventName = "Activity: Remarks";
			} else if (StringUtils.equals(srcName, "Report the record")) {
				eventName = "Activity: Reporting";
			} else {
				eventName = "Activity:" + srcName;
				hasEvent = false;
			}
			vh.eventIdname.setText(eventName);
			// vh.eventimg.setBackgroundResource(hasEvent ?
			// R.drawable.qiandao_hbjl_h
			// : R.drawable.qiandao_qdbf_h);
			vh.eventimg.setBackgroundResource(R.drawable.qiandao_hbjl_h);
			vh.dynamic_event.setOnClickListener(new OnClickOpstion(dynamic,
					OnClickOpstion.OPS_EVENT));
		
//			-----------------
		}else{

			vh.dynamic_event.setVisibility(StringUtils
					.isBlank(dynamic.taskOrEventName) ? View.GONE : View.VISIBLE);
			String srcName = dynamic.taskOrEventName;
			String eventName = "";
			boolean hasEvent = true;
			if (StringUtils.equals(srcName, "记录电话")) {
				eventName = "活动:电话";
			} else if (StringUtils.equals(srcName, "记录短信")) {
				eventName = "活动:短信";
			} else if (StringUtils.equals(srcName, "签到拜访")) {
				eventName = "活动:签到拜访";
			} else if (StringUtils.equals(srcName, "记录邮件")) {
				eventName = "活动:邮件";
			} else if (StringUtils.equals(srcName, "写个备注")) {
				eventName = "活动:备注";
			} else if (StringUtils.equals(srcName, "汇报记录")) {
				eventName = "活动:汇报记录";
			} else {
				eventName = "活动:" + srcName;
				hasEvent = false;
			}
			vh.eventIdname.setText(eventName);
			// vh.eventimg.setBackgroundResource(hasEvent ?
			// R.drawable.qiandao_hbjl_h
			// : R.drawable.qiandao_qdbf_h);
			vh.eventimg.setBackgroundResource(R.drawable.qiandao_hbjl_h);
			vh.dynamic_event.setOnClickListener(new OnClickOpstion(dynamic,
					OnClickOpstion.OPS_EVENT));
		
		}
	}

	private void fillDataCommon(DynamicModel dynamic, ViewHolder vh,
			final int pos) {
		try {
			String url = UrlTools.getTopImage(dynamic.authorId);

//		UserUtils.setLogoRound_z(url, vh.icon, UserUtils
//				.getBackGroudColorByUserIdHash(dynamic.authorId, mContext),
//				UserUtils.getNickRowName(dynamic.authorIdname), mContext);

			ImageLoader.getInstance().displayImage(url , vh.icon, ImageLoaderUtils_circle.MyDisplayImageOptions());
			Bitmap imgphoto = ImageUtils.toRoundBitmap(UserManager.getManager().getLogoId(dynamic.authorId));
			vh.icon.setImageBitmap(imgphoto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		vh.icon.setOnClickListener(new OnClickUserInfo(dynamic));


		// 昵称
		if (TextUtils.isEmpty(dynamic.authorIdname)) {
			if ("en".equals(mEns)) {
				vh.nicheng.setText("No time");
				}else{
					vh.nicheng.setText("暂无");
			}
			
		} else {
			vh.nicheng.setText(dynamic.authorIdname);
//			vh.nicheng.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
		}
		vh.nicheng.setOnClickListener(new OnClickUserInfo(dynamic));

		// 时间
		if (TextUtils.isEmpty(dynamic.createDate)) {
			vh.time.setVisibility(View.INVISIBLE);
//			vh.timeLine.setVisibility(View.INVISIBLE);
		} else {
			vh.time.setVisibility(View.VISIBLE);
			vh.time.setText(dynamic.createDate);
//			vh.timeLine.setVisibility(View.VISIBLE);
//			vh.timeLine.setText(dynamic.createDate);
			Log.d("IIIII", dynamic.createDate);
		}

		// 地址
		boolean hasAddress = StringUtils.isNotBlank(dynamic.address);
		vh.address.setVisibility(hasAddress ? View.VISIBLE : View.GONE);
		vh.address.setText(hasAddress ? "  " + dynamic.address : " ");

		// 收藏
		vh.favourite
				.setImageResource(dynamic.isfavorited ? R.drawable.chatter_favouriteact
						: R.drawable.chatter_favourite);
		vh.shoucang.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				DynamicModel dynamic = mData.get(pos);
				String fileId = dynamic.fileId;
				dynamic.isfavorited = !dynamic.isfavorited;
				ImageView childView = (ImageView) v
						.findViewById(R.id.favourite);
				childView
						.setImageResource(!dynamic.isfavorited ? R.drawable.chatter_favouriteact
								: R.drawable.chatter_favourite);
				DongHuaUtils.startScaleAnimationJavaCode(childView);
				notifyDataSetChanged();
				if (onItemListener != null) {
					onItemListener.onClickCollect(dynamic);
				}
			}
		});

		// 赞(喜欢)
		vh.praised
				.setImageResource(dynamic.ispraised ? R.drawable.chatter_praisedact
						: R.drawable.chatter_praised);
		// 喜欢个数
		vh.countxh.setText(String.valueOf(NumberUtils.toInt(dynamic.praisenum,
				0)));
		// 留言个数
		vh.countly
				.setText(ListUtils.getSize(dynamic.comments) == 0 ? StringUtils.EMPTY
						: String.valueOf(dynamic.comments.size()));
		vh.pinglun.setOnClickListener(new OnClickOpstion(dynamic,
				OnClickOpstion.OPS_COMMIT));
		vh.xihuan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				DynamicModel dynamic = mData.get(pos);
				updatePraised(!dynamic.ispraised, pos);
				ImageView childView = (ImageView) view
						.findViewById(R.id.praied);
				childView
						.setImageResource(!dynamic.ispraised ? R.drawable.chatter_praisedact
								: R.drawable.chatter_praised);
				DongHuaUtils.startScaleAnimationJavaCode(childView);
				if (onItemListener != null) {
					onItemListener.onClickLike(dynamic, view);
				}

			}
		});
		vh.shanchuaa.setVisibility(StringUtils.equals(UserManager.getManager()
				.getUser().userId, dynamic.authorId) ? View.VISIBLE
				: View.GONE);
		// 删除
		vh.shanchuaa.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (onItemListener != null) {
					DynamicModel dynamicModel = getItem(pos);
					onItemListener.onClickDelete(dynamicModel, pos);
				}
			}
		});


		vh.zhengti.setOnClickListener(new OnClickOpstion(dynamic,
				OnClickOpstion.OPS_ALL));

		// 关联
		fillTarget(vh, pos);
Log.d("daodishinali", "欧了这里");
		// event
		fillDataForEvent(vh, dynamic);
		if (!(StringUtils.isBlank(targetid))) {
			fillTarget1(vh, pos);
		}
	}

	private void fillTarget1(ViewHolder vh, int pos) {
		DynamicModel dynamic = getItem(pos);
		vh.targetIdname.setVisibility(View.VISIBLE);
		vh.targetIdlx.setVisibility(View.VISIBLE);
		vh.target.setVisibility(View.VISIBLE);

		String targetType = "";
		String title = "";
		if (targetid.length() >= 4) {
			targetType = targetid.substring(0, 3);
		}
		if ("en".equals(mEns)) {
			if (StringUtils.equals(targetType, "001")) {
				title = "Association →" + "client";
			} else if (StringUtils.equals(targetType, "003")) {
				title = "Association →" + "Contact person";
			} else if (StringUtils.equals(targetType, "004")) {
				title = "Association →" + "Potential customers";
			} else {
				title = "Association →" + "recording";
			}
		}else{
			if (StringUtils.equals(targetType, "001")) {
				title = "关联 →" + "客户";
			} else if (StringUtils.equals(targetType, "003")) {
				title = "关联 →" + "联系人";
			} else if (StringUtils.equals(targetType, "004")) {
				title = "关联 →" + "潜在客户";
			} else {
				title = "关联 →" + "记录";
			}
		}
		vh.targetIdlx.setText(title);
		vh.targetIdname.setText("【" + name + "】");
		dynamic.targetId = targetid;
		vh.target.setOnClickListener(new OnClickOpstion(dynamic,
				OnClickOpstion.OPS_RELATION));
		Log.d("title", title);
	}

	private void fillTarget(ViewHolder vh, int pos) {
		DynamicModel dynamic = getItem(pos);
		Log.d("targetId", dynamic.targetIdname + "::" + dynamic.targetId);
		if (StringUtils.isBlank(dynamic.targetId)) {// 不是关联
			vh.targetIdname.setVisibility(View.GONE);
			vh.targetIdlx.setVisibility(View.GONE);
			vh.target.setVisibility(View.GONE);
			Log.d("zuihoupaole", "最后跑了希望是");
			return;
		}

		vh.targetIdname.setVisibility(View.VISIBLE);
		vh.targetIdlx.setVisibility(View.VISIBLE);
		vh.target.setVisibility(View.VISIBLE);

		String targetType = "";
		String title = "";
		if (dynamic.targetId.length() >= 4) {
			targetType = dynamic.targetId.substring(0, 3);
		}
		if ("en".equals(mEns)) {
			if (StringUtils.equals(targetType, "001")) {
				title = "Association →" + "client";
			} else if (StringUtils.equals(targetType, "003")) {
				title = "Association →" + "Contact person";
			} else if (StringUtils.equals(targetType, "004")) {
				title = "Association →" + "Potential customers";
			} else {
				title = "Association →" + "recording";
			}
		}else{
			if (StringUtils.equals(targetType, "001")) {
				title = "关联 →" + "客户";
			} else if (StringUtils.equals(targetType, "003")) {
				title = "关联 →" + "联系人";
			} else if (StringUtils.equals(targetType, "004")) {
				title = "关联 →" + "潜在客户";
			} else {
				title = "关联 →" + "记录";
			}
		}
//		if (StringUtils.equals(targetType, "001")) {
//			title = "关联 →" + "客户";
//		} else if (StringUtils.equals(targetType, "003")) {
//			title = "关联 →" + "联系人";
//		} else if (StringUtils.equals(targetType, "004")) {
//			title = "关联 →" + "潜在客户";
//		} else {
//			title = "关联 →" + "记录";
//		}
		vh.targetIdlx.setText(title);
		vh.targetIdname.setText("【" + dynamic.targetIdname + "】");
		vh.target.setOnClickListener(new OnClickOpstion(dynamic,
				OnClickOpstion.OPS_RELATION));
		Log.d("title", title + "::" + dynamic.targetIdname + "::"
				+ dynamic.targetId);
		Log.d("zuihoupaole", "最后跑了希望是111");
	}

	private void updatePraised(boolean ispraised, int pos) {
		mData.get(pos).ispraised = ispraised;
		int number = NumberUtils.toInt(mData.get(pos).praisenum, 0);
		mData.get(pos).praisenum = ispraised ? String.valueOf(number + 1)
				: String.valueOf(number > 0 ? number - 1 : 0);
		notifyDataSetChanged();
	}

	private View BindViewForFollow(View convertView) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = mInflater.inflate(R.layout.dynamic_item_follow, null);

			vh.gv = (GridViewForListView) convertView.findViewById(R.id.gv);
			// 获得通用的
			BindViewCommon(convertView, vh);
		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		if("true".equals(tag)) {
			vh.wenben.setMaxLines(10);
		}
		return convertView;
	}

	private View BindViewForLink(View convertView) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = mInflater.inflate(R.layout.dynamic_item_link, null);
			vh.lianjiename = (TextView) convertView
					.findViewById(R.id.lianjielanse);
			vh.linkContainer = (LinearLayout) convertView
					.findViewById(R.id.lianjieurlll);

			BindViewCommon(convertView, vh);

		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		if("true".equals(tag)) {
			vh.wenben.setMaxLines(10);
		}
		return convertView;
	}

	private View BindViewForFile(View convertView) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = mInflater.inflate(R.layout.dynamic_item_file, null);

			vh.aboutpic = (RelativeLayout) convertView
					.findViewById(R.id.aboutpic);
			vh.gv = (GridViewForListView) convertView.findViewById(R.id.gv);
			vh.downwenjian = (TextView) convertView
					.findViewById(R.id.downwenjian);
			vh.downloadpic = (RelativeLayout) convertView
					.findViewById(R.id.downloadpic);
			vh.download = (ImageView) convertView.findViewById(R.id.download);

			BindViewCommon(convertView, vh);

		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		if("true".equals(tag)) {
			vh.wenben.setMaxLines(10);
		}
		return convertView;
	}

	private View BindViewForVote(View convertView) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = mInflater.inflate(R.layout.dynamic_item_vote, null);

			vh.abcapoll = (LinearLayout) convertView
					.findViewById(R.id.abcapoll);// 存放选项
			vh.bttoupiao = (Button) convertView.findViewById(R.id.bttoupiao);// 我要投票
			vh.btnSeeVote = (Button) convertView
					.findViewById(R.id.dynamic_vote_seereulst);// 查看结果
			vh.counttp = (TextView) convertView.findViewById(R.id.countp);// 投票数量

			BindViewCommon(convertView, vh);

		} else {
			vh = (ViewHolder) convertView.getTag();
		}
			
		return convertView;
	}

	private View BindViewForEvent(View convertView) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = mInflater.inflate(R.layout.dynamic_item_event, null);

			vh.eventimg = (ImageView) convertView.findViewById(R.id.eventimg);
			vh.eventIdname = (TextView) convertView
					.findViewById(R.id.eventidname);
			vh.dynamic_event = (LinearLayout) convertView
					.findViewById(R.id.dynamic_event);

			BindViewCommon(convertView, vh);

		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		if("true".equals(tag)) {
			vh.wenben.setMaxLines(10);
		}
		return convertView;
	}

	private View BindViewForRelation(View convertView) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = mInflater.inflate(R.layout.dynamic_item_relat, null);

			BindViewCommon(convertView, vh);

		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		if("true".equals(tag)) {
			vh.wenben.setMaxLines(10);
		}
		return convertView;
	}
	/**
	 * 语音
	 * @param convertView
	 * @return
	 */
	private View BindViewForVoice(View convertView,DynamicModel dynamic,final int pos) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = mInflater.inflate(R.layout.dynamic_item_voice, null);
			vh.gv = (GridViewForListView) convertView.findViewById(R.id.gv);
			// 获得通用的
			BindViewCommon(convertView, vh);
		} else {
			vh = (ViewHolder) convertView.getTag();
		}
	mId = dynamic.id;//语音帖子id
	getVoice(convertView,vh,pos);
		return convertView;
	}

	private void BindViewCommon(View convertView, ViewHolder vh) {
		// top
		vh.icon = (ImageView) convertView.findViewById(R.id.icon);// 头像
		vh.nicheng = (TextView) convertView.findViewById(R.id.nicheng);// 昵称
		vh.time = (TextView) convertView.findViewById(R.id.time);// 时间
//		vh.timeLine = (TextView)convertView.findViewById(R.id.timeLine);
		// 文本内容
		vh.wenben = (TextView) convertView.findViewById(R.id.wbnr);
		//继续读取
		vh.jixu_tv = (TextView) convertView.findViewById(R.id.jixu_tv);
		//投票刷新
		vh.refreshvote = (Button) convertView.findViewById(R.id.refresh_vote);

		//语音
		vh.playerLayout = (LinearLayout) convertView.findViewById(R.id.playerLayout);
		//是否读取语音标识
		vh.voicePoint = convertView.findViewById(R.id.voicePoint);
		vh.viewanim = convertView.findViewById(R.id.id_recorder_anims);
		vh.timeLength = (TextView) convertView.findViewById(R.id.timeLength);
		// 地址
		vh.address = (TextView) convertView.findViewById(R.id.address);
		vh.titleheardyna=(TextView) convertView.findViewById(R.id.title_hear_dyna);
		// footer
		// 收藏
		vh.shoucang = (RelativeLayout) convertView.findViewById(R.id.shoucang);
		vh.favourite = (ImageView) convertView.findViewById(R.id.favourite);
		// 喜欢
		vh.xihuan = (RelativeLayout) convertView.findViewById(R.id.xihuan);
		vh.praised = (ImageView) convertView.findViewById(R.id.praied);
		vh.countxh = (TextView) convertView.findViewById(R.id.countxh);

		// 删除
		vh.shanchuaa = (RelativeLayout) convertView
				.findViewById(R.id.shanchuaq);
		vh.delete = (ImageView) convertView.findViewById(R.id.delete);

		// 评论
		vh.pinglun = (RelativeLayout) convertView.findViewById(R.id.pinglun);
		vh.comment = (ImageView) convertView.findViewById(R.id.comment);
		vh.countly = (TextView) convertView.findViewById(R.id.tvpingluna);

		// 整
		vh.zhengti = (LinearLayout) convertView.findViewById(R.id.zhengti);

		// 关联记录
		vh.target = (LinearLayout) convertView.findViewById(R.id.target);// 容器
		vh.targetIdlx = (TextView) convertView.findViewById(R.id.targetIdlx);// 关联->
		vh.targetIdname = (TextView) convertView
				.findViewById(R.id.targetIdname);// 关联的内容

		// event
		vh.eventimg = (ImageView) convertView.findViewById(R.id.eventimg);
		vh.eventIdname = (TextView) convertView.findViewById(R.id.eventidname);
		vh.dynamic_event = (LinearLayout) convertView
				.findViewById(R.id.dynamic_event);

		convertView.setTag(vh);

	}

	private static class ViewHolder {
		ImageView icon;// 头像
		TextView nicheng;// 昵称
		TextView time;// 时间
		TextView timeLine;//事件轴
		TextView address;// 地址
		TextView wenben;// 文本 内容
		TextView jixu_tv;
		LinearLayout playerLayout;//播放语音
		View voicePoint;//是否读取语音小红点
		View viewanim;
		TextView timeLength;
		TextView titleheardyna;
		// footer
		RelativeLayout shoucang, xihuan, shanchuaa, pinglun;// 容器
		ImageView favourite, praised, delete, comment;// 图片
		TextView countly, countxh;// 数量

		// 整体
		LinearLayout zhengti;

		// 连接
		TextView lianjiename;
		LinearLayout linkContainer;

		// 图片以及文件
		RelativeLayout aboutpic, downloadpic;
		GridViewForListView gv;
		TextView downwenjian;
		ImageView download;

		// 投票
		LinearLayout abcapoll;
		TextView counttp;
		Button bttoupiao;
		Button btnEditVote;// 修改投票
		Button btnSeeVote;// 修改投票
		Button refreshvote;
		// 关联
		TextView targetIdlx;
		TextView targetIdname;
		LinearLayout target;

		// event
		LinearLayout dynamic_event;
		ImageView eventimg;
		TextView eventIdname;

		private TextView mydownload, elow_address;
		private ImageView image;
		private ImageView lianjieimg;
		private ImageView targetimg;
		private RelativeLayout lianjieurl, aboutaddress;
		private LinearLayout abouttoupiao, event, caonilaopo;
		int distanceFromTop;
	}
	private TextView titleheardyna;

	private void setBodyByType(int viewType, ViewHolder vh, DynamicModel dynamic) {

		vh.wenben.setText("");
		vh.titleheardyna.setText("");
		switch (viewType) {
		case TYPE_LINK:
			if ("en".equals(mEns)) {
				vh.titleheardyna.setText("Share links：");
				setBodyNosub( dynamic.body, vh.wenben,vh.jixu_tv);
				}else{
					vh.titleheardyna.setText("分享链接：");
					setBodyNosub(dynamic.body, vh.wenben,vh.jixu_tv);
			}
			
			break;
		case TYPE_FILE:
			List<FeedFile> feedFiles = dynamic.feedFile;
			if (feedFiles != null && feedFiles.size() > 0) {
				FeedFile f = feedFiles.get(0);
				String mimaType = f == null ? "" : f.contentType;
				if ("en".equals(mEns)) {
					if (isImageMima(mimaType)) {
						vh.titleheardyna.setText("Share pictures:");
						setBodyNosub(dynamic.body, vh.wenben,vh.jixu_tv);
					} else {
						vh.titleheardyna.setText("Share files: ");
						setBodyNosub(dynamic.body, vh.wenben,vh.jixu_tv);
					}
					}else{
						if (isImageMima(mimaType)) {
							vh.titleheardyna.setText("分享图片:");
							setBodyNosub(dynamic.body, vh.wenben,vh.jixu_tv);
						} else {
							vh.titleheardyna.setText("分享文件: ");
							setBodyNosub( dynamic.body, vh.wenben,vh.jixu_tv);
						}
				}
				
				
			}
			break;
		case TYPE_FOLLOW:
		case TYPE_EVENT:
			setBodyNosub(dynamic.body, vh.wenben,vh.jixu_tv);
			break;
		case TYPE_RELATION:
			setBodyNosub(dynamic.body, vh.wenben,vh.jixu_tv);
			break;
		case TYPE_VOTE:
			if ("en".equals(mEns)) {
				setBodyNosub( dynamic.body, vh.wenben,vh.jixu_tv);
				}else{
					setBodyNosub( dynamic.body, vh.wenben,vh.jixu_tv);
			}
			
			break;
		}
		vh.wenben.setOnClickListener(new OnClickOpstion(dynamic,
				OnClickOpstion.OPS_ALL));

	}

	private void setBodyNosub(String bodyText, TextView tvBody,TextView jixu) {
		String body = "";
		if(bodyText != null){
			body = Html.fromHtml(bodyText).toString();
		}else{
			body = "";
			bodyText = "";
		}
		String header = "";
		if (body.length() >= 70) {
			header =  bodyText + "...";
		} else {
			header =  bodyText;
		}
		setBody(header, tvBody,jixu);
	}

	private void setBody(String bodyText, TextView tvBody,TextView jixu) {
		int a = 0;
		int b = 0;
		// 这里没有考虑body长度大于100的情况，你自己考虑一下吧

		tvBody.setMovementMethod(LinkMovementMethod.getInstance());

		String pattern = "<a[^>]*>([^<]*)</a>";
		Matcher matcher = Pattern.compile(pattern).matcher(bodyText);

		int lastSpanEndIndex = 0; // 每次匹配成功的字符串的最后索引
		SpannableString spannableStr = null; // "@XXX"
		String aLabelString = null; // a标签，形如"<a href="xxx">fdsafd</a>"

		String Id = null;
		String Name= null;
		while (matcher.find()) {
			a++;
			int index = matcher.start();

			aLabelString = matcher.group();

			tvBody.append(Html.fromHtml(bodyText.substring(lastSpanEndIndex,
					index)));
			b = index;
			try {
				String userIdTemp = aLabelString.substring(aLabelString
						.indexOf("&userid="));
				Id = userIdTemp.substring(userIdTemp.indexOf("=") + 1,
						userIdTemp.indexOf("'"));
				Name = userIdTemp.substring(userIdTemp.indexOf(">")+1,userIdTemp.indexOf("<"));
			} catch (Exception e) {
				// TODO: handle exception
				String userIdTemp = aLabelString.substring(aLabelString
						.indexOf("&id="));
				Id = userIdTemp.substring(userIdTemp.indexOf("=") + 1,
						userIdTemp.indexOf("'"));
				Name = userIdTemp.substring(userIdTemp.indexOf(">")+1,userIdTemp.indexOf("<"));
			}
			
			

			ChatterClickableSpan chatterClickableSpan = new ChatterClickableSpan(
					Id,Name, mContext);

			spannableStr = new SpannableString(Html.fromHtml(aLabelString)
					.toString());

			spannableStr.setSpan(chatterClickableSpan, 0,
					spannableStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

			tvBody.append(spannableStr);

			lastSpanEndIndex = matcher.end();

		}
		if (a == 0) {
			tvBody.setText(Html.fromHtml(bodyText));
			if(tvBody.length()>60) {
				if("true".equals(tag)) {
					jixu.setVisibility(View.GONE);
				}else {
					jixu.setVisibility(View.VISIBLE);
				}

			}else{
				jixu.setVisibility(View.GONE);
			}
		} else {
			if (lastSpanEndIndex < bodyText.length()) {
				tvBody.append(Html.fromHtml(bodyText.substring(
						lastSpanEndIndex, bodyText.length())));
			}
		}
	}

	@Override
	public int getItemViewType(int position) {

		DynamicModel dynamicModel = getItem(position);
		// 先判断是不是 event跟task
		// if (StringUtils.isNotBlank(dynamicModel.taskIdOrEventId)) {
		// return TYPE_EVENT;
		// }
		// 在根据 type 判断
		String type = dynamicModel.feedType;
		if (TextUtils.equals(type, "F")) {
			return TYPE_FOLLOW;
		} else if (TextUtils.equals(type, "L")) {// 连接
			return TYPE_LINK;
		} else if (TextUtils.equals(type, "D")) {// 图文件
			return TYPE_FILE;
		} else if (TextUtils.equals(type, "G")) {// 关系
			return TYPE_RELATION;
		} else if (TextUtils.equals(type, "V")) {// 投票
			return TYPE_VOTE;
		} else if(TextUtils.equals(type, "YY")){
			return TYPE_VOICE;
		}else {
			return TYPE_FOLLOW;
		}
	}

	private boolean isImageMima(String mimaType) {
		return mimaType.equals("jpg") || mimaType.equals("JPG")
				|| mimaType.equals("png") || mimaType.equals("PNG")
				|| mimaType.equals("jpeg") || mimaType.equals("bmp")
				|| mimaType.equals("gif");
	}

	@Override
	public int getViewTypeCount() {
		return TYPECOUNT;
	}

	@Override
	public int getCount() {
		return mData == null || mData.size() == 0 ? 0 : mData.size();
	}

	@Override
	public DynamicModel getItem(int position) {
		return mData.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void setOnItemtListener(OnItemListener onItemListener) {
		this.onItemListener = onItemListener;
	}

	/**
	 * 点击事件
	 * 
	 * @author wangzhiqiang
	 * @date 2015-8-10 上午9:09:44
	 * 
	 */
	public interface OnItemListener {

		/**
		 * 点击访问连接
		 * 
		 * @param t
		 */
		public void onClickLink(DynamicModel t);

		/**
		 * 点击logo
		 * 
		 * @param
		 */
		public void onClickUser(DynamicModel t);

		/**
		 * 评论
		 * 
		 * @param
		 */
		public void onClickComment(DynamicModel t);// 评论

		/**
		 * 喜欢
		 * 
		 * @param
		 * @param v
		 */
		public void onClickLike(DynamicModel t, View v);// 赞

		/**
		 * 事件 或者活动 任务
		 * 
		 * @param
		 * @param
		 */
		public void onClickEventOrTask(DynamicModel t);

		/**
		 * 收藏
		 * 
		 * @param t
		 */
		public void onClickCollect(DynamicModel t);// 收藏

		/**
		 * 点击删除
		 * 
		 * @param t
		 */
		public void onClickDelete(DynamicModel t, int pos);// 删除

		/**
		 * 点击下载
		 * 
		 * @param t
		 */
		public void onClickDownload(DynamicModel t, int pos);// 如果是文件下载文件

		/**
		 * 点击关联
		 * 
		 * @param t
		 */
		public void onClickRelation(DynamicModel t);//

		/**
		 * 点击投票
		 * 
		 * @param t
		 */
		public void onClickVote(DynamicModel t, String option);//

		/**
		 * 整体点击
		 * 
		 * @param t
		 */
		public void onClickBody(DynamicModel t);// 整体监听
	}

	private class OnClickUserInfo implements OnClickListener {
		private DynamicModel t;

		public OnClickUserInfo(DynamicModel t) {
			super();
			this.t = t;
		}

		@Override
		public void onClick(View v) {
			if (onItemListener != null) {
				onItemListener.onClickUser(t);
			}
		}
	}

	private class OnClickOpstion implements OnClickListener {
		public static final int OPS_FAVOURITE = 1;
		public static final int OPS_EVENT = 2;
		public static final int OPS_COMMIT = 3;
		public static final int OPS_RELATION = 4;
		public static final int OPS_ALL = 5;
		private DynamicModel t;
		private int ops;

		public OnClickOpstion(DynamicModel t, int ops) {
			super();
			this.t = t;
			this.ops = ops;
		}

		@Override
		public void onClick(View v) {
			if (onItemListener == null) {
				return;
			}
			switch (ops) {
			case OPS_FAVOURITE:
				onItemListener.onClickCollect(t);
				break;
			case OPS_EVENT:
				//点击活动事件
				onItemListener.onClickEventOrTask(t);
				break;
			case OPS_COMMIT:
				onItemListener.onClickComment(t);
				break;
			case OPS_RELATION:
				// 关联点击事件
				onItemListener.onClickRelation(t);
				break;
			case OPS_ALL:
				Log.d("OPS_ALL", "进入body");
				onItemListener.onClickBody(t);
				break;
			default:
				break;
			}

		}
	}

	public void addData(List<DynamicModel> data) {
		mData.addAll(data);
		notifyDataSetChanged();
	}
	public void changeDatax(List<DynamicModel> data) {
        mData.clear();
        mData = data;
        notifyDataSetInvalidated();
	}

	public void changeData(List<DynamicModel> data) {
		mData.clear();
		mData = data;
		notifyDataSetChanged();
	}

	public int getCurrentVoteOps() {
		return currentVoteOpts;
	}

	public void clear() {
		mData.clear();
		notifyDataSetChanged();
	}

	@Override
	public void notifyDataSetChanged() {
		super.notifyDataSetChanged();
		currentVoteOpts = 0;
	}

	public void removeItem(DynamicModel t) {
		mData.remove(t);
		notifyDataSetChanged();
	}

	// 人名单击的监听
	public static class ChatterClickableSpan extends ClickableSpan {
		String iId;
		Context context;
		String name;
		public ChatterClickableSpan(String userId,String name, Context context) {
			super();
			this.iId = userId;
			this.context = context;
			this.name = name;
		}

		@Override
		public void onClick(View widget) {

			Intent intent = new Intent(context,
					Myinformation.class);
			SaveTemporaryData.mSmart="";
			intent.putExtra(UserInfoActivity.KEY_USERID, iId);
			intent.putExtra("name", name);
			context.startActivity(intent);
//			Intent intent = new Intent(context, NewUserInfoActivity.class);
//			intent.putExtra(UserInfoActivity.KEY_USERID, iId);
//			context.startActivity(intent);
		}

	}
	private void getVoice(final View view,ViewHolder vh,final int pos) {
       final ViewHolder mViewHolder = vh;
       vh.voicePoint.setTag(pos);
       setVoiceTime(vh,pos);
       
        vh.playerLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Toast.makeText(mContext, "你 点  击 了 第 "+pos+" 个 按 钮 ！", 1).show();
				if (mBamr) {
					DynamicModel dynamic = mData.get(pos);
					String fileId = dynamic.fileId;
					getCache(mViewHolder,view,fileId,pos);
					mBamr = false;
				}else{
					VoiceMediaManager.pause();
					mViewHolder.viewanim.setBackgroundResource(R.drawable.v_anim3);
					mBamr = true;
				}
				
			}
		});
	}
	public void setVoiceTime(ViewHolder vh,final int pos){
		DynamicModel dynamic = mData.get(pos);
		String s = dynamic.yylength;//获取语音时间
//	  
		LayoutParams lParams=vh.playerLayout.getLayoutParams();
		if (s==null) {
			return ;
		}
		BigDecimal bg = new BigDecimal(dynamic.yylength);
		double fTime = bg.setScale(1, BigDecimal.ROUND_DOWN).doubleValue();
		int round = (int) Math.round(fTime);
//		int round = Integer.valueOf(dynamic.yylength);
		if (round>60) {
			lParams.width=(int) (mMaxItemWith);
		}else{
			if (round<=3) {
				lParams.width=(int) (mMinItemWith+70);
			}else{
				lParams.width=(int) ((mMinItemWith+70)+(mMaxItemWith-120)/60f*round);
			}
			
		}
		vh.playerLayout.setLayoutParams(lParams);
		if (round<60) {
			if (round<10) {
				vh.timeLength.setText("00' "+"0"+String.valueOf(round)+"''");
			}else{
				vh.timeLength.setText("00' "+String.valueOf(round));
			}
			
		}else{
			int mInt= round/60;
			int mYu = round%60;
			if (mInt<10) {
				if (mYu<10) {
					vh.timeLength.setText("0"+String.valueOf(mInt)+"' "+"0"+mYu+"''");
				}else{
					vh.timeLength.setText("0"+String.valueOf(mInt)+"' "+mYu);
				}
				
			}else{
				if (mYu<10) {
					vh.timeLength.setText(String.valueOf(mInt)+"' "+"0"+mYu+"''");
				}else{
					vh.timeLength.setText(String.valueOf(mInt)+"' "+mYu+"''");
				}
				
			}
		}
		
	}
	public void downLoadVoice(ViewHolder vh, final View view,String voiceId, int pos) {
//		Toast.makeText(mContext, "下载中，稍后播放", Toast.LENGTH_SHORT).show();
		final ViewHolder mvh = vh;
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
		params.addBodyParameter("serviceName", "downloadYY");
		params.addBodyParameter("id",voiceId);
		
		Log.d("-------------------------", "点击下载语音 url ==   " + UrlManager.getInterfaceUrl()+"?binding="+RunTimeManager.getInstance().getServerBinding()+"&"+"serviceName="+"downloadYY"+"&id="+voiceId);

		utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params,new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						Log.d("-------------------------", "下载语音失败Failure。。。" + arg1);
						Toast.makeText(mContext, "下载语音失败", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						String result = arg0.result;
						Log.d("-------------------------", "下载语音成功Success_down_voice:     " + result);
                       parseVoiceJson(view,result,mvh);
					}
					
				});
		int tag = (int) vh.voicePoint.getTag();
		if (tag==pos) {
			vh.voicePoint.setVisibility(View.INVISIBLE);
		}
	}
		public void parseVoiceJson(View view,String json, ViewHolder vh){
			JSONObject mObj = null ;
			 try {
				 mObj = new JSONObject(json);
				 JSONObject upYY = mObj.getJSONObject("data");
				 mVoiceData = upYY.getString("YYData");
				 mVoiceName = upYY.getString("id");
				 mVoiceType = upYY.getString("YYType");
				 mVoiceTime = upYY.getString("YYTimeLength");
//				 if ("caf".equals(mVoiceType)) {
//					 parseForCaf(view,mVoiceData,mVoiceName,vh);
//				}else{
					 parseForAmr(view,mVoiceData,mVoiceName,vh);
//				}
				 
			} catch (JSONException e) {
				
				e.printStackTrace();
			}
		}
		public void parseForAmr(View view,String voice, String mVoiceName, ViewHolder vh){
			String dir = Environment.getExternalStorageDirectory()+ "/aaaaaa";//创建文件夹
			File files = new File(dir);
			if (!files.exists()) {
				files.mkdirs();
			}
//			File filea = new File(files, mVoiceName+".amr");
			File filea = new File(files, mVoiceName+".caf");
			
			try {
				decoderBase64File(view,voice,filea,mVoiceName,vh);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d("woaini", e.getMessage()+"::");
				e.printStackTrace();
			} 
		}
		 /**
		  * 将base64字符解码保存文件
		  * @param base64Code
		  * @param targetPath
		 * @param mVoiceName 
		 * @param vh 
		  * @throws Exception
		  */
		public void decoderBase64File(View view,String base64Code, File targetPath, String mVoiceName, ViewHolder vh)
				   throws Exception {
				  byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
				  FileOutputStream out = new FileOutputStream(targetPath);
				  out.write(buffer);
				  out.close();
				  playerVoice(view,mVoiceName,vh,buffer);
				 }
		public void playerVoice(View view, String mVoiceName, ViewHolder vh, byte[] buffer){
			setAnim(vh);
			String dira = Environment.getExternalStorageDirectory()+ "/aaaaaa/"+mVoiceName+".caf";//创建文件夹
			Log.d("woaini    ", dira);
			setDir(dira);
			final ViewHolder mVh = vh;
			if ("caf".equals(mVoiceType)) {
				playSound(buffer);
//				mVh.viewanim.setBackgroundResource(R.drawable.v_anim3);
			}else{
				VoiceMediaManager.playSound(dira, new OnCompletionListener() {
					
					@Override
					public void onCompletion(MediaPlayer mp) {
						// TODO Auto-generated method stub
						mBamr = true;
						mVh.viewanim.setBackgroundResource(R.drawable.v_anim3);
					}
				});
			}
			
		}
	public void setDir(String dira){
		
		SharedPreferences pref = mContext.getSharedPreferences("data",mContext.MODE_PRIVATE); 
		SharedPreferences.Editor editor = pref.edit(); 
		editor.putString(mId,dira); 
		editor.commit();
	}
		public void getCache(ViewHolder mViewHolder, View view, String fileId, int pos){
			SharedPreferences pref = mContext.getSharedPreferences("data",mContext.MODE_PRIVATE); 
			String name = pref.getString(mId,"");//第二个参数为默认值 
			String s = name;
			String ss = s;
			downLoadVoice(mViewHolder,view,fileId,pos);
//			if (name==null) {
//				downLoadVoice(mViewHolder,view,fileId,pos);
//			}else{
//				setCacheVoice(name,mViewHolder);
//			}
			
		}
		public void setCacheVoice(String dira, final ViewHolder mViewHolder){
//			setAnim(mViewHolder);
			VoiceMediaManager.playSound(dira, new OnCompletionListener() {
				
				@Override
				public void onCompletion(MediaPlayer mp) {
					// TODO Auto-generated method stub
					mBamr = true;
					mViewHolder.viewanim.setBackgroundResource(R.drawable.v_anim3);
				}
			});
		}
		public void setAnim(ViewHolder vh){

			vh.viewanim.setBackgroundResource(R.drawable.voice_play);
			AnimationDrawable drawable = (AnimationDrawable) vh.viewanim
					.getBackground();
			drawable.start();
		}
		/**
		 * 播放caf格式的语音、、、
		 * @param soundData
		 */
		 private void playSound(byte[] soundData) {  
		        int index = 0;  
		        int offset = 0;  
		        // 8000 byte every second  
		        final int minBufsize = AudioTrack.getMinBufferSize(8000,  
		                AudioFormat.CHANNEL_OUT_STEREO,// The channel  
		                AudioFormat.ENCODING_PCM_16BIT);  
		      
		        mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,  
		                8000,  
		                AudioFormat.CHANNEL_OUT_STEREO,  
		                AudioFormat.ENCODING_PCM_16BIT,  
		                minBufsize,  
		                AudioTrack.MODE_STREAM);  
		      
		        mAudioTrack.play();  
		        while (true) {  
		            try {  
		                offset = index * minBufsize;  
		                if (offset >= soundData.length) {  
		                    break;  
		                }  
		      
		                mAudioTrack.write(soundData, offset, minBufsize);  
		            } catch (Exception e) {  
		                break;  
		            }  
		      
		            index++;  
		        }  
		      
		        mAudioTrack.release();  
		    }  
		 public void parseForCaf(View view,String voice, String mVoiceName, ViewHolder vh){
			 try {
				byte[] buffer = new BASE64Decoder().decodeBuffer(voice);
				playSound(buffer);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 public void getHeight(View view){
			 view.measure(0,0);
			int  height=view.getMeasuredHeight();
		 }
}
